package com.dylovedz.javafxphone.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dylovedz.javafxphone.controller.vo.PhoneExcelVO;
import com.dylovedz.javafxphone.controller.vo.WechatExcelVO;
import com.dylovedz.javafxphone.service.MaterialTask;
import com.dylovedz.javafxphone.service.WechatService;
import com.dylovedz.javafxphone.util.ExcelUtil;
import com.dylovedz.javafxphone.util.PhoneUtil;
import com.google.i18n.phonenumbers.NumberParseException;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishArticles;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishItem;
import me.chanjar.weixin.mp.bean.freepublish.WxMpFreePublishList;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.config.impl.WxMpMapConfigImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;

/**
 * 主界面控制器
 *
 * @author dylovedz
 * @date 2023/03/09 16:50
 */
@Slf4j
@FXMLController
public class WechatController implements Initializable {

    // 主容器
    public Pane wechatPane;
    @Autowired
    private WechatService wechatService;

    public Button btnAlert, btnChooseFile;
    public Button btnSearch;
    public TextField phoneText;
    public TextArea phoneGeoText;
    public Tooltip btnChooseFileTip;
    public Button btnChooseDir;
    public Tooltip btnChooseDirTip;
    public Button btnExport;
    public TextField appIdText;
    public TextField appSecretText;

    private String inFile;
    private String outDir;
    private File lastFile;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        log.info("initialize: {}", location.getPath());
    }

    /**
     * 弹出框按钮单击事件
     * @param actionEvent
     */
    public void onBtnAlertClick(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setContentText("当前时间：" + DateUtil.now());
        alert.show();
    }

    /**
     * 选择文件按钮单机事件
     * @param actionEvent
     */
    public void onBtnChooseFileClick(ActionEvent actionEvent) {
        Window window = wechatPane.getScene().getWindow();
        FileChooser fileChooser = new FileChooser();
        // 文件类型过滤器
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Excel files (*.xls, *.xlsx)", "*.xls", "*.xlsx");
        fileChooser.getExtensionFilters().add(filter);
        if (ObjectUtil.isNotNull(lastFile)) {
            fileChooser.setInitialDirectory(lastFile);
        }

        // ...
        File file = fileChooser.showOpenDialog(window);
        String fileName = file == null ? "" : file.getName();
        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();

        if (file != null) {
            btnChooseFile.setText(fileAbsolutePath);
            btnChooseFileTip.setText(fileAbsolutePath);
            inFile = fileAbsolutePath;
            lastFile = FileUtil.file(file.getParent());
            /*Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("文件路径：" + fileAbsolutePath);
            alert.show();*/
        }
    }

    /**
     * 查询公众号信息
     * @param actionEvent
     */
    public void onBtnSearchClick(ActionEvent actionEvent) {
        String appid = appIdText.getText();
        String appSecret = appSecretText.getText();
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        if (StrUtil.isBlank(appid)) {
            alert.setContentText("请输入appId");
            alert.show();
            return;
        }

        if (StrUtil.isBlank(appSecret)) {
            alert.setContentText("请输入appSecret");
            alert.show();
            return;
        }

        if (StrUtil.isBlank(outDir)) {
            alert.setContentText("请选择导出目录");
            alert.show();
            return;
        }

        try {
            WxMpServiceImpl wxMpService = new WxMpServiceImpl();
            WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpDefaultConfigImpl();
            wxMpDefaultConfig.setAppId(appid);
            wxMpDefaultConfig.setSecret(appSecret);
            wxMpService.setWxMpConfigStorage(wxMpDefaultConfig);

            ForkJoinPool forkJoinPool = new ForkJoinPool();
            int allTask = 1277/20;
            Future<List<WechatExcelVO>> future = forkJoinPool.submit(new MaterialTask(wxMpService, wechatService, 0, allTask, outDir));
            List<WechatExcelVO> wechatExcelList = future .get();
            wechatExcelList.sort(new Comparator<WechatExcelVO>() {
                @Override
                public int compare(WechatExcelVO o1, WechatExcelVO o2) {
                    return o1.getOffset() - o2.getOffset();
                }
            });
            phoneGeoText.setText("总发文数为：" + wechatExcelList.size());
            // 关闭
            forkJoinPool.shutdown();
            String date = DateUtil.format(DateUtil.date(), "MMddHHmmss");
            File file = FileUtil.file(FileUtil.file(outDir), "article" + date + ".xlsx");
            ExcelUtil.write(file, "文章导出", WechatExcelVO.class, wechatExcelList);
            alert.setContentText("导出成功");
            alert.show();

        } catch (Exception exception) {
            phoneGeoText.setText("程序异常：" + exception.getMessage());
        }


    }

    /**
     * 选择导出目录
     * @param actionEvent
     */
    public void onBtnChooseDirClick(ActionEvent actionEvent) {
        Window window = wechatPane.getScene().getWindow();
        DirectoryChooser folderChooser = new DirectoryChooser();
        if (ObjectUtil.isNotNull(lastFile)) {
            folderChooser.setInitialDirectory(lastFile);
        }
        // ...
        File file = folderChooser.showDialog(window);
        String fileName = file == null ? "" : file.getName();
        String fileAbsolutePath = file == null ? "" : file.getAbsolutePath();
        if (file != null) {
            btnChooseDir.setText(fileAbsolutePath);
            btnChooseDirTip.setText(fileAbsolutePath);
            outDir = fileAbsolutePath;
            lastFile = file;
            /*Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setContentText("文件路径：" + fileAbsolutePath);
            alert.show();*/
        }
    }

    /**
     * 导出逻辑处理
     * @param actionEvent
     * @throws IOException
     * @throws NumberParseException
     */
    public void onBtnExportClick(ActionEvent actionEvent) throws IOException, NumberParseException {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        if (StrUtil.isBlank(inFile)) {
            alert.setContentText("请选择查询的excel");
            alert.show();
            return;
        }
        if (StrUtil.isBlank(outDir)) {
            alert.setContentText("请选择导出目录");
            alert.show();
            return;
        }
        BufferedInputStream stream = FileUtil.getInputStream(inFile);
        List<PhoneExcelVO> readList = ExcelUtil.read(stream, PhoneExcelVO.class);
        if (ObjectUtil.isEmpty(readList)) {
            alert.setContentText("excel没有数据或头部格式不正确，请确保头部存在“手机号”列");
            alert.show();
            return;
        }
        for (PhoneExcelVO phoneExcelVO : readList) {
            if (!PhoneUtil.isValid(phoneExcelVO.getPhone())) {
                phoneExcelVO.setCarrier("格式错误");
                phoneExcelVO.setGeo("格式错误");
            } else {
                String geo = PhoneUtil.getGeo(phoneExcelVO.getPhone());
                if (ObjectUtil.equals(geo, "中国")) {
                    Map<String, String> phoneGeo = PhoneUtil.getPhoneByHttp(phoneExcelVO.getPhone());
                    phoneExcelVO.setGeo(phoneGeo.get("geo"));
                    phoneExcelVO.setCarrier(phoneGeo.get("carrier"));
                } else {
                    phoneExcelVO.setGeo(geo);
                    phoneExcelVO.setCarrier(PhoneUtil.getCarrier(phoneExcelVO.getPhone()));
                }

            }
        }
        String date = DateUtil.format(DateUtil.date(), "MMddHHmmss");
        File file = FileUtil.file(FileUtil.file(outDir), "phone" + date + ".xlsx");
        ExcelUtil.write(file, "归属地查询", PhoneExcelVO.class, readList);
        alert.setContentText("导出成功");
        alert.show();
    }
}
